package com.fuelwallet.wizard;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.fuelwallet.R;
import com.fuelwallet.model.CarProfile;
import com.fuelwallet.model.CarProfileHandle;
import com.fuelwallet.model.CurrentAccount;
import com.fuelwallet.model.FuelPrice;
import com.fuelwallet.model.FuelPriceHandle;
import com.fuelwallet.model.PriceUtility;
import com.fuelwallet.view.BaseMapActivity;

public class SetupFueltypeActivity extends Activity{	
	public static final int MESSAGE_INTERNET_TIMEOUT = -1;
	public static final int DIALOG_EXIT = 10;
	
	// member view elements
	private Spinner spinner;
	private Button btn_next;
	private EditText edt_displacement;
	
	private FuelPriceHandle priceHandler;	
	private PriceUtility priceUtility;
	private CarProfileHandle carHandler;
	private CurrentAccount curAcc;
	
	private ProgressDialog dialog;
		
	private String fuelName;
	private String carName;
	private List<String> displayList;
	private ArrayAdapter<String> spinnerAdapter;
	private SpinnerItemListener spinnerItemListener;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setup_fueltype);  
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        
        btn_next = (Button) findViewById(R.id.btn_next_fueltype);       
        spinner = (Spinner) findViewById(R.id.spinner2);     
        edt_displacement = (EditText) findViewById(R.id.edittext_displacement);
        priceHandler = new FuelPriceHandle(this); 
        priceUtility = new PriceUtility(this, mHandler);
        carHandler = new CarProfileHandle(this);
        curAcc = new CurrentAccount(this);
        FuelThread fuelThread = new FuelThread(priceUtility, mHandler);
        
        Intent intent = getIntent();
        carName = intent.getStringExtra(SetupAccountActivity.CAR_NAME);
		btn_next.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {			
				String disp = edt_displacement.getText().toString();
				float displacement;

				try {
					if (disp.length() == 0)
						displacement = 2.2f;
					else
						displacement = Float.valueOf(disp);

					CarProfile newCar = new CarProfile(carName, displacement, fuelName);
					carHandler.open();
					carHandler.putCarProfile(newCar);
					carHandler.close();
					curAcc.open();
					curAcc.setCurrentAccount(newCar);
					curAcc.close();
				} catch (NumberFormatException e) {
					Toast.makeText(SetupFueltypeActivity.this,
							"Please enter numbers only!", Toast.LENGTH_SHORT).show();
					return;
				}
				
				// start BaseMapActivity
				Intent intent = new Intent(SetupFueltypeActivity.this, BaseMapActivity.class);
				SetupFueltypeActivity.this.startActivity(intent);				
				SetupFueltypeActivity.this.finish();
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
			}
		});
		
		displayList = new ArrayList<String>();
		spinnerItemListener = new SpinnerItemListener();
		
		spinnerAdapter = new ArrayAdapter<String>(this, 
	    		android.R.layout.simple_spinner_item, displayList);
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(spinnerAdapter);
	    spinner.setOnItemSelectedListener(spinnerItemListener);
			
		fuelThread.start();
		
		Message msg = new Message();
		msg.what = MESSAGE_INTERNET_TIMEOUT;
		mHandler.sendMessageDelayed(msg, 8000);
		
		dialog = ProgressDialog.show(this, "", "Obtaining fuel price. Please wait...", true, true);
		dialog.show();
    }
	
	protected Dialog onCreateDialog(int id){
		switch(id){
		case DIALOG_EXIT:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want to exit?")
			       .setCancelable(false)
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                SetupFueltypeActivity.this.finish();
			                android.os.Process.killProcess(android.os.Process.myPid());
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			return alert;
		default:
			return null;
		}
	}
	
	// disable BACK key
	public void onBackPressed() {
		showDialog(DIALOG_EXIT);		
	}
		
	private void setupSpinner(){
		priceHandler.open();
			List<String> fuelnameList = priceHandler.getFuelNameList();
			displayList.clear();
			for(int i = 0; i < fuelnameList.size(); i++){
				FuelPrice fuelpriceTemp = priceHandler.getFuelPrice(fuelnameList.get(i));
				displayList.add(fuelpriceTemp.getfuelName());
			}
		priceHandler.close();
		
		spinnerAdapter.notifyDataSetChanged();		
	}
		
	private class SpinnerItemListener implements OnItemSelectedListener {
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	    	fuelName = parent.getItemAtPosition(pos).toString();	
	    	//Toast.makeText(SetupFueltypeActivity.this, fuelName + " is set!", Toast.LENGTH_LONG).show();
	    }
	    public void onNothingSelected(AdapterView<?> parent) {
	    	return;
	    }
	}

	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case PriceUtility.MESSAGE_UPDATE_OK:
				setupSpinner();
				dialog.dismiss();
				break;
			case MESSAGE_INTERNET_TIMEOUT:				
				if(dialog.isShowing()){
					dialog.dismiss();
					Toast.makeText(SetupFueltypeActivity.this, "Cannot access Internet! ", Toast.LENGTH_SHORT).show();
					SetupFueltypeActivity.this.finish();
				}
				break;
			}
			return;
		}
	};
	
	private class FuelThread extends Thread{
		private Handler _handler;
		private PriceUtility _util;
		
		public FuelThread(PriceUtility util, Handler handler){
			_handler = handler;
			_util = util;		
		}
		
		public void run(){
			_util.startExecution();
			_util.analyze();
			_util.updateDatabase(false);				
		}
	}
}